package chapter18;

import java.io.*;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-03-29 下午3:23
 */
public class Worm implements Serializable {
    private static Random random = new Random(47);
    private Data[] data = {
            new Data(random.nextInt(10)),
            new Data(random.nextInt(10)),
            new Data(random.nextInt(10))
    };

    private Worm next;
    private char c;

    public Worm(int i, char c) {
        System.out.println("worm constructor: " + i);
        this.c = c;
        if (--i > 0) {
            next = new Worm(i, (char) (c + 1));
        }
    }

    public Worm() {
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Worm worm = new Worm(6, 'a');
        System.out.println("worm=" + worm);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worm.out"));
        out.writeObject("worm storage\n");
        out.writeObject(worm);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("worm.out"));
        String s = (String) in.readObject();
        Worm worm1 = (Worm) in.readObject();
        System.out.println(s + "w2=" + worm1);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out2 = new ObjectOutputStream(bout);
        out2.writeObject("worm storage\n");
        out2.writeObject(worm);
        out2.flush();


        ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
        s = (String) in2.readObject();
        Worm worm2 = (Worm) in2.readObject();
        System.out.println(s + "w3=" + worm2);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder(":");
        builder.append(c);
        builder.append("(");
        for (Data dat : data) {
            builder.append(dat);
        }
        builder.append(")");
        if (next != null) {
            builder.append(next);
        }

        return builder.toString();
    }
}
